import React, { useState, useEffect } from 'react';
import { connect } from 'umi';
// connect 高阶组件 把redux中的数据和当前组件进行关联
import {
  Card,
  Space,
  Table,
  Button,
  Tooltip,
  Badge,
  message,
  Popconfirm,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { ReloadOutlined } from '@ant-design/icons';
import { useKey } from '@/hooks';
import { searchListItem } from '@/j_api';
import setleIndex from '@/pages/index.less';

interface DataType {
  key: string;
  keyword: string;
  count: number;
}

function SearchList(props: any) {
  let { searchlist, total, dispatch, lodingboolean } = props;
  searchlist = useKey(searchlist);
  const [pageInfo] = useState({ page: 1, pageSize: 12 });
  useEffect(() => {
    dispatch({ type: 'search/INIT', pageInfo });
  }, []);

  const onChange = (page: number, pageSize: number) => {
    dispatch({
      type: 'search/INIT',
      pageInfo: {
        page,
        pageSize,
      },
    });
  };
  // 删除
  const confirm = (id: string) => {
    searchListItem(id)
      .then((res: any) => {
        if (res.statusCode === 200) {
          message.success('删除成功');
          dispatch({ type: 'search/INIT', pageInfo });
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  // 多选删除
  const confirmAll = (itemAll: any) => {
    itemAll.forEach((item: any) => {
      searchListItem(item)
        .then((res: any) => {
          if (res.statusCode === 200) {
            message.success('操作成功');
            dispatch({ type: 'search/INIT', pageInfo });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    });
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '搜索词',
      dataIndex: 'keyword',
      key: 'keyword',
    },
    {
      title: '搜索量',
      key: 'count',
      render: (_, record: any) => (
        <Badge
          overflowCount={999}
          className="site-badge-count-109"
          count={record.count}
          style={{ backgroundColor: '#52c41a' }}
        />
      ),
    },
    {
      title: '搜索时间',
      key: 'createAt',
      render: (_, record: any) => (
        <Space size="middle">
          {new Date(record.createAt).toLocaleString()}
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'operation',
      render: (_, record: any) => (
        <Popconfirm
          title="确认删除这个搜索记录？"
          onConfirm={() => confirm(record.id)}
          okText="确定"
          cancelText="取消"
        >
          <a>删除</a>
        </Popconfirm>
      ),
    },
  ];

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const hasSelected = selectedRowKeys.length > 0;

  return (
    <div className={setleIndex.mt20}>
      <Card
        title={
          hasSelected ? (
            <div style={{ marginBottom: 16 }}>
              <Popconfirm
                title="确认删除？"
                onConfirm={() => confirmAll(selectedRowKeys)}
                okText="确定"
                cancelText="取消"
              >
                <Button danger>删除</Button>
              </Popconfirm>
            </div>
          ) : (
            ''
          )
        }
        extra={
          <Tooltip placement="top" title="刷新">
            <ReloadOutlined
              onClick={() => {
                dispatch({ type: 'search/INIT', pageInfo });
              }}
              style={{
                cursor: 'pointer',
              }}
            />
          </Tooltip>
        }
      >
        <Table
          pagination={{
            // 总数量
            total,
            // 默认的每条页数
            defaultPageSize: 12,
            // 指定每页可以显示多少条
            pageSizeOptions: [8, 12, 24, 36],
            // 用于显示数据总量和当前数据顺序
            showTotal: (total) => {
              return <>共{total}条</>;
            },
            onChange: onChange,
            // 是否展示 pageSize 切换器，当 total 大于 50 时默认为 true
            showSizeChanger: true,
          }}
          rowSelection={rowSelection}
          columns={columns}
          dataSource={searchlist}
          loading={lodingboolean}
        />
      </Card>
    </div>
  );
}
// connect接收两个参数
// 1. 函数 mapStateToProps
const mapStateToProps = (state: any) => {
  const { search } = state;
  return search;
};
export default connect(mapStateToProps)(SearchList);
